"""
用户模型
"""
from sqlalchemy import Column, String, Float, Integer, DateTime, JSON, Text, Enum as SQLEnum
from sqlalchemy.sql import func
from app.core.database import Base
import enum


class UserRole(enum.Enum):
    """用户角色"""
    USER = "user"
    VENUE_MANAGER = "venue_manager"
    CITY_MANAGER = "city_manager"
    SUPER_ADMIN = "super_admin"


class User(Base):
    """用户表"""
    __tablename__ = "users"
    
    id = Column(String(36), primary_key=True, index=True)
    nick_name = Column(String(100), nullable=False)
    avatar = Column(String(500))
    phone = Column(String(20), unique=True, index=True)
    password_hash = Column(String(255))
    
    # 角色和权限
    role = Column(String(20), default="user", comment="用户角色")
    
    # 微信相关
    wechat_openid = Column(String(100), unique=True, index=True)
    wechat_unionid = Column(String(100), unique=True, index=True)
    
    # 用户信息
    positions = Column(JSON)  # ["forward", "midfielder"]
    rating = Column(Float, default=0.0)
    city_id = Column(String(36))
    city_name = Column(String(100))
    team_ids = Column(JSON)  # 加入的球队ID列表
    
    # 统计数据
    monthly_bookings = Column(Integer, default=0)
    total_matches = Column(Integer, default=0)
    total_spent = Column(Float, default=0.0)
    favorite_venue = Column(String(36))
    
    # 收藏场地
    favorite_venues = Column(JSON)  # 收藏的场地ID列表
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "nickName": self.nick_name,
            "avatar": self.avatar,
            "phone": self.phone,
            "positions": self.positions or [],
            "rating": self.rating,
            "cityId": self.city_id,
            "cityName": self.city_name,
            "teamIds": self.team_ids or [],
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "stats": {
                "monthlyBookings": self.monthly_bookings,
                "totalMatches": self.total_matches,
                "totalSpent": self.total_spent,
                "favoriteVenue": self.favorite_venue
            }
        }

